<template>
  <div class="search-box">
    <!-- 搜索区域 -->
    <form class="searchForm" action="/">
      <van-search v-model="searchText" background="#3296fa" show-action placeholder="请输入搜索关键词" @search="onSearch"
        @cancel="$router.go(-1)" @focus="showSearchResult=false" />
    </form>

    <!-- 搜索结果 -->
    <SearchResult :value="searchText" v-if="showSearchResult" />
    <!-- 搜索历史 -->
    <SearchHistory v-else-if="!searchText" :history="history" @delHistory="onSearch" />
    <!-- 搜索建议 -->
    <SearchSuggestion @search="onSearch" :value="searchText" v-else />
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import SearchResult from './components/search-result.vue'
import { getItem, setItem } from '@/utils/storage.js'
const HMTT_HISTORY = 'hmtt_history'
export default {
  name: 'search',
  data () {
    return {
      // 搜索表单绑定数据
      searchText: '',
      // 控制搜素结果显示状态
      showSearchResult: false,
      // 搜索历史
      history: getItem(HMTT_HISTORY) || []
    }
  },
  methods: {
    onSearch (value) {
      // 储存搜索历史
      this.history.unshift(value)
      this.history = [...new Set(this.history)]
      // 把搜索建议添加到搜索框中
      this.searchText = value
      // 显示搜索结果
      this.showSearchResult = true
    }
  },
  computed: {},
  watch: {
    history (val) {
      setItem(HMTT_HISTORY, val)
    }
  },
  filters: {},
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  created () { },
  mounted () { }
}
</script>

<style scoped lang='less'>
.search-box {
  .searchForm {
    position: sticky;
    top: 0;
    z-index: 2;
  }
  // 取消样式
  .van-search__action {
    color: #fff;
  }
}
</style>
